import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Button, Dropdown } from 'antd';
import React, { useMemo } from 'react';
interface OpearteButtonGroupPorps {
  items?: {
    text: React.ReactNode;
    key: string;
    onClick(): void;
    disabled?: boolean;
  }[];
}

export function OpearteButtonGroup({ items = [] }: OpearteButtonGroupPorps) {
  const btnAndDropDownObj = useMemo<{
    btnList: OpearteButtonGroupPorps['items'];
    dorpDownItems?: MenuProps['items'];
  }>(() => {
    if (items.length <= 3) {
      return { btnList: items };
    } else if (items.length > 3) {
      const tempBtnList = items.slice(0, 2);
      const tempDorpDownItems: MenuProps['items'] = items
        .slice(2)
        .map((item) => ({
          key: item.key,
          label: <span onClick={item.onClick}>{item.text}</span>,
          disabled: item.disabled,
        }));
      return {
        btnList: tempBtnList,
        dorpDownItems: tempDorpDownItems,
      };
    }
    return {
      btnList: [],
    };
  }, [items]);

  return (
    <div className="td-operation">
      {btnAndDropDownObj.btnList?.map((v) => {
        return (
          <Button
            size="small"
            key={v.key}
            type="text"
            onClick={v.onClick}
            style={{ color: '#1890ff' }}
            disabled={v.disabled}
          >
            {v.text}
          </Button>
        );
      })}
      {btnAndDropDownObj.dorpDownItems &&
        btnAndDropDownObj.dorpDownItems.length && (
          <Dropdown menu={{ items: btnAndDropDownObj.dorpDownItems }}>
            <p className="operation-text">
              更多
              <DownOutlined className="text-icon" />
            </p>
          </Dropdown>
        )}
    </div>
  );
}
